package com.idea.zd.sys.train.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zzy
 * @Date 2018/9/10 下午2:15
 */
public class NioTest {
    /**
     * 输入字节流
     * @param args
     * @throws IOException
     */
    public static void main(String args[]) throws IOException{

        /*List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");

        list.remove("3");
        System.out.println(list.size());*/

        NioWrite();






    }


    public static void NioReader() throws IOException{
        File file = new File(".");

        /*for(String f:file.list()){
            System.out.println(f);
        }*/
        //创建字节流
        FileInputStream fileInputStream = new FileInputStream("ss.fxml");
        // 从FileInputStream创建用于输入的FileChannel
        FileChannel fileChannel = fileInputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        //返回长度
        int hasRead = 0;

        System.out.println("限制是：" + byteBuffer.limit() + "\n容量是：" + byteBuffer.capacity() + "\n位置是：" + byteBuffer.position());
        int length = -1;
        while ((length = fileChannel.read(byteBuffer)) != -1) {

            /*
             * 注意，读取后，将位置置为0，将limit置为容量, 以备下次读入到字节缓冲中，从0开始存储
             */
            byteBuffer.clear();
            byte[] bytes = byteBuffer.array();
            System.out.println("start..............");

            String str = new String(bytes, 0, length);
            System.out.println(str);
            //System.out.write(bytes, 0, length);

            System.out.println("end................");

            System.out.println("限制是：" + byteBuffer.limit() + "容量是：" + byteBuffer.capacity() + "位置是：" + byteBuffer.position());

        }

        fileChannel.close();

        fileInputStream.close();
    }

    public static void NioWrite() throws IOException{
        File file = new File(".");

        /*for(String f:file.list()){
            System.out.println(f);
        }*/
        //创建字节流
        FileOutputStream fileOutputStream = new FileOutputStream("ss1.fxml");
        // 从FileInputStream创建用于输入的FileChannel
        FileChannel fileChannel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        String ss = "1231231231233123";

        byteBuffer.put(ss.getBytes());
        //byteBuffer.clear(); //此处必须要调用buffer的flip方法
        byteBuffer.put("sss".getBytes());
        byteBuffer.clear(); //此处必须要调用buffer的flip方法
        fileChannel.write(byteBuffer);

        fileChannel.close();

        fileOutputStream.close();
    }

}
